package com.example.webrestfulcrud.controller;

import com.example.webrestfulcrud.dao.ItemRepository;
import com.example.webrestfulcrud.pojo.TbItem;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Optional;

@Controller
public class ItemController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    ItemRepository itemRepository;

    @GetMapping("/items")
    public ModelAndView items() {
        List<TbItem> all = this.itemRepository.findAll();
        ModelAndView modelAndView = new ModelAndView();

        modelAndView.addObject("itemList", all);
        modelAndView.setViewName("list");
        return modelAndView;
    }

    @PostMapping("/item")
    public ModelAndView addItem(TbItem tbItem, Integer panelContentId, ModelAndView modelAndView) {
        logger.info("panelId是：" + panelContentId);
        logger.info("此次添加的商品是：" + tbItem);

        MongoCollection<Document> item = this.mongoTemplate.getCollection("item");

        FindIterable<Document> sort = item.find().projection(new Document("_id", "1")).sort(new Document("_id", -1));

        for (Document document : sort) {
            Long id = document.getLong("_id");
            tbItem.setId(id + 1);
            break;
        }


        modelAndView.setViewName("redirect:/user/main.html");

        this.itemRepository.save(tbItem);

        return modelAndView;
    }


    @GetMapping("/item/{itemId}")
    public ModelAndView findItemAndEditIt(ModelAndView modelAndView, @PathVariable Long itemId){

        Optional<TbItem> byId = this.itemRepository.findById(itemId);

        modelAndView.addObject("itemForEdit",byId.get());

        modelAndView.setViewName("/edit");

        return modelAndView;
    }


    @PutMapping("/item")
    public ModelAndView updateItem(ModelAndView modelAndView,TbItem item,Boolean statusCheck){

        if(statusCheck){
            item.setStatus(1);
        }else{
            item.setStatus(0);
        }
        this.itemRepository.save(item);

        modelAndView.setViewName("redirect:/user/main.html");

        return modelAndView;
    }

    @DeleteMapping("/item/{deletedItemId}")
    public ModelAndView deleteItemById(@PathVariable Long deletedItemId){

        this.itemRepository.deleteById(deletedItemId);

        return new ModelAndView("redirect:/user/main.html");
    }
}
